//
//  ProdListTableViewController.m
//  QS
//
//  Created by Centling on 14-4-24.
//  Copyright (c) 2014年 seas.cheng. All rights reserved.
//

#import "ProdListTableViewController.h"
#import "ProdListCell.h"
#import "QTProductDetailViewController.h"
#import "QTClient.h"
#import "UIImageView+AFNetworking.h"
#import "Global.h"
#import "UIImageView+UIActivityIndicatorForSDWebImage.h"

//use count to record the current items of news
static NSInteger count;
#define REFRESH_HEADER_HEIGHT 52.0f

@interface ProdListTableViewController ()

@end

@implementation ProdListTableViewController
@synthesize textPull, textRelease, textLoading, refreshFooterView, refreshLabel, refreshArrow, refreshSpinner, hasMore, textNoMore;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title=_keyWord;
    NSLog(@"====================The productName:%@ the companyName:%@ the productNumber:%@ the brand:%@",self.Filter_prod_name,self.Filter_prod_factory,self.Filter_prod_puid,self.Filter_prod_brand);
    refreshSpinnerForNews = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    refreshSpinnerForNews.frame = CGRectMake([UIScreen mainScreen].applicationFrame.size.width/2.0-50, [UIScreen mainScreen].applicationFrame.size.height/2.0-100, 100, 100);
    refreshSpinnerForNews.hidesWhenStopped = YES;
    
    NSLog(@"start reflesh");
    [self.view addSubview:refreshSpinnerForNews];
    refreshSpinnerForNews.hidden = NO;
    [refreshSpinnerForNews startAnimating];
    
    self.tableView.separatorStyle=NO;
    [self addPullToRefreshFooter];
    [self setupStrings];
    _tapCgr=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];

}

-(void)viewDidAppear:(BOOL)animated
{
//    [self.hideTabbarDelegate showTabbar];
    [self RemoveSubviews];
    [self.view removeGestureRecognizer:_tapCgr];
    if (items == nil || [items count] == 0) {
        count=1;
        NSNumber * index=[[NSNumber alloc]initWithInt:count];
        
        [[QSClient instance] loadProductList:index
                                  maxResults:@8
                                 productName:self.Filter_prod_name     ==nil?@"":self.Filter_prod_name
                            manufacturerName:self.Filter_prod_factory  ==nil?@"":self.Filter_prod_factory
                                 productType:self.Filter_prod_puid     ==nil?@"":self.Filter_prod_puid
                                       brand:self.Filter_prod_brand    ==nil?@"":self.Filter_prod_brand
                                       keyWord:self.Filter_prod_brand    ==nil?@"":self.Filter_prod_brand
                             completionBlock:^(ProductList *productList, NSError *error){
            
            //add information label
            [refreshSpinnerForNews stopAnimating];
            refreshSpinnerForNews.hidden = YES;
            
            UILabel *info_label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-125, self.view.frame.size.height/2-60, 250, 40)];
            info_label.backgroundColor = [UIColor clearColor];
            info_label.textColor = [UIColor blackColor];
            info_label.textAlignment = NSTextAlignmentCenter;
            info_label.font = [UIFont fontWithName:@"Arial-BoldItalicMT" size:15];
            

            if (productList == nil) {
                info_label.text = @"加载失败，点击屏幕，重新加载";
                info_label.tag = 100;
                [self.view addSubview:info_label];
                self.tableView.scrollEnabled = NO;
                self.tableView.allowsSelection = NO;
                [self.view addGestureRecognizer:_tapCgr];
                
                
            }
            // if the list is get successfully but it is an empty list
            else if ([(NSArray *)productList.list count] == 0) {
                info_label.text = @"产品列表为空";
                info_label.tag = 101;
                [self.view addSubview:info_label];
                self.tableView.allowsSelection = NO;
                self.tableView.scrollEnabled = NO;

            }
            else{
                self.tableView.scrollEnabled = YES;
                items= [[NSMutableArray alloc]initWithArray:productList.list];
                [self.tableView reloadData];
                self.tableView.separatorStyle=YES;
                self.tableView.allowsSelection = YES;

                count=count+1;
            }

        }];
    }
}

-(BOOL)RemoveSubviews
{
    UIView * view=nil;
    
    for (view in [self.view subviews])
    {
        if (view.tag == 100 || view.tag == 101) {
            [view removeFromSuperview];
        }
    }
    
    return true;
}

-(void)tap:(id)sender
{
    refreshSpinnerForNews.hidden = NO;
    [refreshSpinnerForNews startAnimating];

    [self viewDidAppear:NO];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    //return 8;
    return [items count];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *paperCell = @"ProdListCell";
    ProdListCell *cell = (ProdListCell *)[tableView dequeueReusableCellWithIdentifier:paperCell];
    
    if (cell ==nil) {
        NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"ProdListCell" owner:self options:nil];
        cell = (ProdListCell *)[nibArray objectAtIndex:0];
    }
 
    //make sure the product list 中 每一条都不是空的
    List *tempprod = (List*)[items objectAtIndex:indexPath.row];
    if (tempprod == nil) {
        NSLog(@"no data for this product!");
        cell.ProdName.text=@"该项产品为空";
        //return 进行下一个cell
        return cell;
    }
    // 产品名称显示
    cell.ProdName.text=((List*)[items objectAtIndex:indexPath.row]).productName;
    
    
    // 产品缩略图显示
    NSURL *url=[NSURL URLWithString:[self convertPicURL:(tempprod.filePath==nil?@"":tempprod.filePath)]];
    [cell.Prodimage setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        if (image == nil) {
            [cell.Prodimage setImage:[UIImage imageNamed:@"暂无图片.png"]];
        }
    } usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray ];
    
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [refreshSpinnerForNews stopAnimating];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}



-(NSString *)convertPicURL:(NSString *)url
{
    NSString *picURL=url;
    NSRange range_http = [url rangeOfString:@"http:"];
    NSRange range_HTTP = [url rangeOfString:@"HTTP:"];
    if ((range_http.length==0)&&(range_HTTP.length==0)) {
        picURL=[productInfoPicUrl stringByAppendingString:url==nil?@"":url];
    }
    return  picURL;
}

#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QTProductDetailViewController *productviewController=[[QTProductDetailViewController alloc] init];
    
    //传递参数到 product detail 页面
     List *tempprod = (List*)[items objectAtIndex:indexPath.row];
    if (tempprod == nil) {
        productviewController.puid = tempprod.puid;
    }
    else
    {
        productviewController.puid = tempprod.puid==nil?@"":tempprod.puid;
    }
    
    [self.navigationController pushViewController:productviewController animated:YES];
    NSLog(@"%@",@"运行didSelectRowIndexPath");
}

- (void)setupStrings{
    textPull    = @"上拉刷新...";
    //textRelease = @"释放开始刷新...";
    textLoading = @"正在加载...";
    textNoMore  = @"没有更多内容了...";
    hasMore = YES;
}

-(void)addPullToRefreshFooter{
    NSLog(@"add footer");
    refreshFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, self.tableView.frame.size.height-60, 320, REFRESH_HEADER_HEIGHT)];
    refreshFooterView.backgroundColor = [UIColor clearColor];
    
    refreshLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, REFRESH_HEADER_HEIGHT)];
    refreshLabel.backgroundColor = [UIColor clearColor];
    refreshLabel.font = [UIFont boldSystemFontOfSize:12.0];
    refreshLabel.textAlignment = NSTextAlignmentCenter;
    
    refreshArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]];
    refreshArrow.frame = CGRectMake(floorf((REFRESH_HEADER_HEIGHT - 27) / 2),
                                    (floorf(REFRESH_HEADER_HEIGHT - 44) / 2),
                                    27, 44);
    
    refreshSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    refreshSpinner.frame = CGRectMake(floorf(floorf(REFRESH_HEADER_HEIGHT - 20) / 2), floorf((REFRESH_HEADER_HEIGHT - 20) / 2), 20, 20);
    refreshSpinner.hidesWhenStopped = YES;
    
    [refreshFooterView addSubview:refreshLabel];
    //[refreshFooterView addSubview:refreshArrow];
    [refreshFooterView addSubview:refreshSpinner];
    [self.tableView addSubview:refreshFooterView];
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (isLoading) return;
    isDragging = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (isLoading && scrollView.contentOffset.y > 0) {
        // Update the content inset, good for section headers
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, REFRESH_HEADER_HEIGHT, 0);
    }else if(!hasMore){
        refreshLabel.text = self.textNoMore;
        refreshArrow.hidden = YES;
    }else if (isDragging && scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom) <= 0 ) {
        // Update the arrow direction and label
        [UIView beginAnimations:nil context:NULL];
        refreshArrow.hidden = NO;
        if (scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom) <= -REFRESH_HEADER_HEIGHT) {
            // User is scrolling above the header
            refreshLabel.text = self.textRelease;
            [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
        } else { // User is scrolling somewhere within the header
            refreshLabel.text = self.textPull;
            [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
        }
        [UIView commitAnimations];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (isLoading || !hasMore) return;
    isDragging = NO;
    
    //    CGPoint offset = scrollView.contentOffset;
    //    CGRect bounds = scrollView.bounds;
    //    CGSize size = scrollView.contentSize;
    //    UIEdgeInsets inset = scrollView.contentInset;
    //    CGFloat currentOffset = offset.y + bounds.size.height - inset.bottom;
    //
    //    CGFloat maximumOffset = size.height;
    //
    //    (maximumOffset - currentOffset) <= -REFRESH_HEADER_HEIGHT)
    
    //上拉刷新
    if(scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom) <= -REFRESH_HEADER_HEIGHT && scrollView.contentOffset.y > 0){
        NSLog(@"load new data");
        [self startLoading];
    }
}

- (void)startLoading {
    isLoading = YES;
    
    // Show the header
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    self.tableView.contentInset = UIEdgeInsetsMake(REFRESH_HEADER_HEIGHT, 0, 0, 0);
    
    refreshLabel.text = self.textLoading;
    refreshArrow.hidden = YES;
    [refreshSpinner startAnimating];
    [UIView commitAnimations];
    
    // Refresh action!
    [self refresh];
}

- (void)stopLoading {
    isLoading = NO;
    
    // Hide the header
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDidStopSelector:@selector(stopLoadingComplete:finished:context:)];
    //self.newsTableView.contentInset = UIEdgeInsetsZero;
    UIEdgeInsets tableContentInset = self.tableView.contentInset;
    //CGRect barFrame=self.navigationController.navigationBar.frame;
    tableContentInset.top = 52.0+15;
    
    self.tableView.contentInset = tableContentInset;
    [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
    [UIView commitAnimations];
}

- (void)stopLoadingComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    // Reset the header
    NSLog(@"%f",self.tableView.contentSize.height);
    if(hasMore==TRUE)
    {
        refreshLabel.text = self.textPull;
        refreshArrow.hidden = NO;
    }
    [refreshFooterView setFrame:CGRectMake(0, self.tableView.contentSize.height, 320, 0)];
    
    [refreshSpinner stopAnimating];
}


- (void)refresh {
    [self performSelector:@selector(addItem) withObject:nil afterDelay:2.0];
}

- (void)addItem {
    // Add a new time
    /*
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
     NSString *now = [dateFormatter stringFromDate:[NSDate date]];
     
     for(int i = 0; i < 10 ; i ++){
     [items addObject:[NSString stringWithFormat:@"%@ %d", now,i]];
     }
     */
    NSLog(@"add items");
    NSLog(@"the added count is %ld",(long)count);
    NSNumber * index=[[NSNumber alloc]initWithInt:count];
    [[QSClient instance] loadProductList:index
                              maxResults:@8
                             productName:self.Filter_prod_name     ==nil?@"":self.Filter_prod_name
                        manufacturerName:self.Filter_prod_factory  ==nil?@"":self.Filter_prod_factory
                             productType:self.Filter_prod_puid     ==nil?@"":self.Filter_prod_puid
                                   brand:self.Filter_prod_brand    ==nil?@"":self.Filter_prod_brand
                                   keyWord:self.Filter_prod_brand    ==nil?@"":self.Filter_prod_brand
                         completionBlock:^(ProductList *productList, NSError *error){
                             //check the result
        if (productList == nil) {
            self.hasMore = NO;
            refreshLabel.text = self.textNoMore;
        }
        else {
            count++;
            for (int i=0;i<[productList.list count];i++)
            {
                
                [items addObject:[productList.list objectAtIndex:i]];
                //count++;
                NSLog(@"the number of items:%lu",(unsigned long)[items count]);
            }
            //[self.newsTableView reloadData];
            //没有更多内容了
            if ([productList.list count] < 8)
            {
                self.hasMore = NO;
                refreshLabel.text = self.textNoMore;
            }
            NSLog(@"start load first time");
            [self.tableView reloadData];
        }
        [self stopLoading];

    }];
    
   }



@end
